//
// Created by zhaog on 31/03/17.
//

#include "meta_svr_interface.h"
#include "protocol/TBinaryProtocol.h"
#include "protocol/TProtocol.h"
#include "transport/TTransport.h"
#include <transport/TBufferTransports.h>
#include <transport/TSocket.h>
#include "common.hpp"

using namespace apache::thrift;
using namespace apache::thrift::protocol;
using namespace apache::thrift::transport;
using std::string;
namespace meta_svr{

    int MetaSvrInterface::GetMeta(std::set<meta::MetaStruct>& metas,string beg_time,string end_time,string busi_type,string uid,string label,bool order_asc, unsigned long limit,string staff_id){

        boost::shared_ptr<TSocket> socket;
        boost::shared_ptr<TTransport> transport;
        boost::shared_ptr<TProtocol> protocol;

        socket = boost::shared_ptr<TSocket>(new TSocket(_meta_svr_ip, _port));
        transport = boost::shared_ptr<TTransport>(new TFramedTransport(socket));
        protocol = boost::shared_ptr<TProtocol>(new TBinaryProtocol(transport));

        transport->open();
        boost::shared_ptr<meta_svr::MetaSvrClient> client;
        client = boost::shared_ptr<meta_svr::MetaSvrClient>(new meta_svr::MetaSvrClient(protocol));

        meta_svr::MetaRequest request;
        srand((unsigned)common::DateTime::CurUsec());
        request.req_id=rand();
        request.my_busi="img_svr";
        request.staff_id=staff_id;
        request.req_body.action=meta_svr::Action::ENUM_META_DETAIL_UID;
        if(busi_type=="YY.LIVE2"){
            request.req_body.busi_type=BusiType::ENUM_BUSI_TYPE_YYLIVE2;
        }else if(busi_type=="YY.LIVE"){
            request.req_body.busi_type=BusiType::ENUM_BUSI_TYPE_YYLIVE;
        }else if(busi_type=="BIGO"){
            request.req_body.busi_type=BusiType::ENUM_BUSI_TYPE_IMG_BIGO;
        } else if(busi_type=="BIGO.VIDEO.V2"){
            request.req_body.busi_type=BusiType::ENUM_BUSI_TYPE_VIDEO_BIGO;
        }

        request.req_body.key=uid;
        request.req_body.beg_time=beg_time;
        request.req_body.end_time=end_time;
        request.req_body.order_asc=order_asc;
        request.req_body.limit=(int64_t)limit;
        request.req_body.label=label;
        MetaResponse response;
        client->GetMetas(response,request);

        if(response.status==StatusEnum::ENUM_STATUS_ERR){
            transport->close();
            return -1;
        }
       // metas=response.res_body.metas;
        for(vector<meta::MetaStruct>::iterator it=response.res_body.metas.begin();it!=response.res_body.metas.end();it++){
            metas.insert(*it);
        }
        transport->close();
        return response.res_body.count;
    }

    void MetaSvrInterface::Init(string meta_svr_ip, unsigned int port) {
        _meta_svr_ip=meta_svr_ip;
        _port=port;
    }
}
